"use strict";
define(["commonUI", "laydate", "template", "drawer","global", "validate", "select2", "datatables", "plupload"], function (
    commonUI, laydate, template, Drawer,global
) {
    var projectId=1;
    var user = null;
    var globalEquipmentId = null
    var globalEquipmentMaintainId = null;
    //传给后台的参数
    var param = {
        pageNumber: 1,
        pageSize: 10
    };
    var table21 = "";
    var app = {
        init: function () {
            user = global.getLoginUser();
            $(".username").text(user.userName)
            this.eventBind();
            this.initSelect();
            this.renderTable();
            this.intDrawer();
        },
        // 筛选项初始化
        initSelect: function () {
            global.get("/admin/project/listByUser",function (res) {
                if (res.success) {
                    var demoData = [];
                    var projects = res.data.projects;
                    var flag = false;
                    projects.forEach(item=>{
                        var m = {};
                        m.id = item.id;
                        m.text = item.name;
                        if(flag==false){
                            m.selected=true;
                            flag = true;
                            projectId = item.id;
                        }
                        demoData.push(m);
                    })
                    $("#relatePro").select2({
                        width: "222px",
                        data:demoData,
                        minimumResultsForSearch: -1
                    });
                    $("#relatePro").on("change",function(){
                        var data = $(this).val();
                        projectId = data;
                        table21.ajax.reload();
                    });
                } 
            },);
        },
        // 渲染表格
        renderTable: function () {
            table21 = $('#standard_table').DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                ordering: false,
                serverSide: true,
                destroy: true,
                // scrollX: true,
                columns: [{
                    title: '序号',
                    data: "number",
                    width: 30
                }, {
                    title: '设备保养名称',
                    data: "name",
                    width: 70
                }, {
                    title: '所属项目',
                    data: "projectName",
                    width: 100
                }, {
                    title: '关联设备名称',
                    data: "equipmentName",
                    width: 100
                },{
                    title: '型号',
                    data: "modelNum",
                    width: 70
                },{
                    title:'所属系统分类',
                    data:"sysclassName",
                    width:70
                },{
                    title:'春季保养时间',
                    data:"springMaintainDate",
                    width:70,
                    render: function (data) {
                        if(data==null || data.trim() == ""){
                            return "本年度尚未保养";
                        }else{
                            return data.substr(0,10);
                        }
                    }

                },{
                    title:'秋季保养时间',
                    data:"autumnMaintainDate",
                    width:70,
                    render: function (data) {
                        if(data==null || data.trim() == ""){
                            return "本年度尚未保养";
                        }else{
                            return data.substr(0,10);
                        }
                    }

                },{
                    title:'备注',
                    data:"description",
                    width:100,
                },{
                    title: '操作',
                    orderable: false,
                    width: 100,
                    render: function (data, type, full) {
                        return '<a class="classify" data-id="' + full.id + '">参数设置</a>' +
                        '<a class="edit" data-id="' + full.id + '">修改</a>' +
                        '<a class="del-single" data-id="' + full.id + '">删除</a>'
                    },
                }],
                lengthMenu: [[15, 25, 50, 100], ["15条/页", "25条/页", "50条/页", "100条/页"]],
                columnDefs: [{
                    targets: [1, 2, 3, 4, 5],
                    render: function (data) {//其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                select: {
                    // 可选择的配置有： 'api'、'single'、'multi'、'os'、'multi+shift'
                    style: 'multi',
                    // 控制是否在左下角显示选中信息
                    info: false,
                    selector: 'td:first-child',
                    orderable: false
                },
                order: [],
                language: {
                    sEmptyTable: '<div class="blank-icon"><p class="msg"><i class="aidicon aidicon-emoticon-sad"></i> 没有搜到任何数据</p></div>'
                },
                ajax: function (params, callback, setting) {
                    if(projectId==null){
                        Dialog.toast("请先选择项目", {"intent":"warn"});
                        return;
                    }
                    // 表格逻辑
                    $('#standard_table_wrapper thead>tr>.select-checkbox').removeClass('selected');
                    $("#delete_all").prop("disabled", true);
                    //排序参数
                    var sortType = "",
                        sortName = "";
                    if (params.order.length > 0) {
                        sortType = params.order[0].dir;
                        sortName = params.columns[params.order[0].column].data;
                    }
                    param.pageNumber = (params.start / params.length) + 1;
                    param.pageSize = params.length;
                    param.projectId = projectId;
                    param.keyword = $("#search_val").val()
                    global.get("/admin/equipmentMaintain/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param);
                },
                initComplete: function (settings, json) {
                    var html = '<li data-curIndex="all" class="all-col"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">全部展示</span></label></div></li>';
                    for (var i = 0; i < settings.aoColumns.length; i++) {
                        if (i == 0) {
                            html += '<li data-curIndex="' + i + '"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">勾选列</span></label></div></li>';
                        } else {
                            html += '<li data-curIndex="' + i + '"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">' + settings.aoColumns[i].sTitle + '</span></label></div></li>';
                        }

                    }
                    $(".dropdown-col-menu").append(html);
                    $('.dropdown-col-menu>li input').change(function () {
                        if ($(this).closest('li').attr('data-curIndex') == "all") { //点击全部
                            if ($(this).is(':checked')) {
                                table21.columns().visible(true);
                                $(this).closest('li').siblings('li').find('input').prop("checked", true)
                            } else {
                                table21.columns().visible(false);
                                $(this).closest('li').siblings('li').find('input').prop("checked", false)
                            }
                        } else { //点击每一列
                            var _index = parseInt($(this).closest('li').attr('data-curIndex'), 10);
                            if ($(this).is(':checked')) {
                                table21.columns(_index).visible(true);
                            } else {
                                table21.columns(_index).visible(false);
                            }

                            // 控制全选的样式
                            var colLength = table21.columns().count();
                            var colSelect = $('.dropdown-col-menu > li[data-curIndex != all] input:checked').length;
                            if (colSelect == colLength) {
                                $('.dropdown-col-menu .all-col input').prop("checked", true);
                            } else {
                                $('.dropdown-col-menu .all-col input').prop("checked", false);
                            }
                        }
                    });

                    //计算列定制下拉的位置
                    var leftPx = "-" + ($(".dropdown-col-menu").width() - 30) + "px";
                    $(".dropdown-col-menu").css("left", leftPx);

                }
            });
            

            // 去掉选中
            table21.on('deselect', function (e, dt, type, indexs) {
                // $(e.target).find('thead>tr>.select-checkbox').removeClass('selected');
                $(e.target).closest('.dataTables_scroll').find('.dataTables_scrollHead').find('thead>tr>.select-checkbox').removeClass('selected');
                var selectedLength = table21.rows({
                    selected: true
                }).count();
                if (selectedLength == 0) {
                    $("#export").prop("disabled", true);
                    $("#delete_all").prop("disabled", true);
                    $(".dropdown-opt-con .btn").prop("disabled", true);
                }
            });
            // 点击全选
            $('#standard_table_wrapper .select-checkbox1').click(function (e) {

                var $parent = $(this).parent('th');
                $parent.toggleClass('selected');
                if ($parent.hasClass('selected')) {
                    $(this).parents('#standard_table_wrapper').find('tbody tr').each(function (i) {
                        table21.row(i).select()
                    });
                } else {
                    $(this).parents('#standard_table_wrapper').find('tbody tr').each(function (i) {
                        table21.row(i).select(false)
                    });
                }
            });
            // 勾选其中一项
            table21.on('select', function (e, dt, type, indexs) {
                // 选中行数
                var selectedLength = table21.rows({
                    selected: true
                }).count();
                $("#export").prop("disabled", false);
                $("#delete_all").prop("disabled", false);
                $(".dropdown-opt-con .btn").prop("disabled", false);
                // 所有行数行数
                var allLength = table21.rows().count();
                // selectedLength === allLength && $(e.target).find('thead>tr>.select-checkbox').addClass('selected');
                selectedLength === allLength && $(e.target).closest('.dataTables_scroll').find('.dataTables_scrollHead').find('thead>tr>.select-checkbox').addClass('selected');
            });
        },
        // 初始化参数设置
        initClassifyTable: function (equipmentMaintainId) {
            var equipmentMaintainParams = [];
            global.get("/admin/equipmentMaintain/param/list/"+equipmentMaintainId,function (res) {
                if (res.success) {
                    equipmentMaintainParams = res.data.equipmentMaintainParams;
                }
            },null,null,false);
            sysClassTable=$('#grid-demo-1').DataTable({
                data: equipmentMaintainParams,
                deferRender: true,
                destroy: true,
                paging: false,
                searching: false,
                info: false,
                ordering: false,
                scrollY: 380,
                scrollCollapse: true,
                language: {
                    sEmptyTable: '<div class="blank-icon"><p class="msg"><i class="aidicon aidicon-emoticon-sad"></i> 没有搜到任何数据</p></div>'
                },
                columns: [
                    {
                        title: "参数名称",
                        data: "name",
                        width: "70%",
                        render: function (data) {
                            if (data) {
                                return "<div class='text-overflow' title='" + data + "'>" + data + "</div>";
                            } else {
                                return "-";
                            }
                        }
                    },{
                        title: "数值",
                        data: "value",
                        width: "70%",
                        render: function (data) {
                            if (data) {
                                return "<div class='text-overflow' title='" + data + "'>" + data + "</div>";
                            } else {
                                return "-";
                            }
                        }
                    },{
                        title: "顺序(小值优先显示)",
                        data: "sort",
                        width: "70%",
                        render: function (data) {
                            if (data) {
                                return "<div class='text-overflow' title='" + data + "'>" + data + "</div>";
                            } else {
                                return "-";
                            }
                        }
                    },{
                        title: "操作",
                        data: "id",
                        width: "40%",
                        render: function (data, type, full) {
                            return '<a class="classify-edit" data-id="' + full.id + '" data-name="'+full.name+'" data-value="'+full.value+'" data-sort="'+full.sort+'" data-toggle="modal" data-target="#editModal">修改</a>' +
                                    '<a class="classify-del" data-id="' + full.id + '" id="popover-' + full.id + '" data-toggle="popover" data-placement="auto top">删除</a>';
                        },
                    }
                ],
                initComplete: function(settings, json) {
                    $('[data-toggle="popover"]').each(function(i,v) {
                        var id = $(v).data("id");
                        $(v).popover({
                            html: true,
                            container: 'body',
                            // container: window.top.document.body,
                            content: '<div style="line-height:16px;">' +
                                '<i class="aidicon aidicon-close-circle" style="float:left;line-height:16px;margin-right:5px;color:#F53B3B;"></i>' +
                                '<span>你确定要删除这项内容吗？</span>' +
                                '<div class="text-right margin-top-small-2">' +
                                '<button  type="button" class="cancel btn btn-default btn-sm margin-right-small-2">取消</button>' +
                                '<button  type="button" class="btn btn-primary btn-sm delete-classify" data-id="'+id+'">确定</button>' +
                                '</div>'
                        });
                    })
                    
                }
            });
        },
        //抽屉
        intDrawer: function () {
            // 新增抽屉
            var addDrawerOpts = {
                title: "",
                data: {},
                content: template("addFormTpl"),
                onClosed:function () {
                },
                button: [
                    {
                        label: "取消",
                        intent: "default",
                        click:function () {
                            app.addDrawer.close();
                        }
                    },
                    {
                        label: "提交",
                        intent: "primary",
                        click: function () {
                            if (!$(".addForm").valid()) {
                                return false;
                            }
                            var data = {};
                            data.id = $("#id1").val()
                            data.name =$("#name1").val()
                            data.equipmentId =$("#equipmentId").val()
                            data.maintainNumber = $("#maintainNumber").val() 
                            data.projectId = projectId;
                            data.description = $("#description").val();
                            data.modelNum = $("#modelNum").val();
                            global.post("/admin/equipmentMaintain/saveOrUpdate",response=>{
                                if(response.success){
                                    app.addDrawer.close();
                                    table21.ajax.reload(null,false);
                                }else{
                                    Dialog.toast(response.message, {"intent":"warn"});
                                }
                            },JSON.stringify(data))
                            
                        }
                    }
                ]
            };
            app.addDrawer = new Drawer(addDrawerOpts);
            // 关联设备参数
            var relationDrawerOpts = {
                title: "关联设备参数",
                data: {},
                content: template("relationTpl"),
                onClosed:function () {
                },
                button: [
                    {
                        label: "取消",
                        intent: "default",
                        click:function () {
                            app.relationDrawer.close();
                        }
                    },
                    {
                        label: "保存",
                        intent: "primary",
                        click: function () {
                            var deviceIds = [];
                            $(".device-checked").each(function(){
                                if($(this).is(":checked")){
                                    deviceIds.push($(this).attr("deviceId"))
                                }
                            })
                            global.get("/admin/equipment/grant?id="+globalEquipmentId + "&deviceIds="+deviceIds,function (res) {
                                if (res.success) {
                                    app.relationDrawer.close();
                                }else{
                                    Dialog.toast(res.message, {"intent":"warn"});
                                }
                            });
                        }
                    }
                ]
            };
            app.relationDrawer = new Drawer(relationDrawerOpts);
        },
        /** 事件绑定 */
        eventBind: function () {
            // 新增
            $('#add').on('click', function () {
                globalEquipmentId = null;
                var editInfo = {status:1};
                var content = template("addFormTpl", {data: editInfo});
                app.addDrawer.renderOption({title: "新增",content:content});
                app.addDrawer.open();
                var equipments = [];
                global.get("/admin/equipment/listAll?projectId="+projectId,function (res) {
                    if (res.success) {
                        res.data.equipments.forEach(item=>{
                            var m = {};
                            m.id = item.id;
                            m.text = item.name;
                            equipments.push(m);
                        });
                    } 
                },null,null,false);
                $("#equipmentId").select2({
                    data:equipments,
                    minimumResultsForSearch: -1
                });
               
            });
            // 编辑
            $(document).on("click", ".edit", function () {
                var equipmentMaintainId = $(this).attr("data-id");
                globalEquipmentId = equipmentMaintainId;
                var editInfo = null;
                global.get("/admin/equipmentMaintain/"+equipmentMaintainId,function(response){
                    if(response.success){
                        editInfo = response.data.equipmentMaintain;
                        console.log(editInfo)
                    }else{
                        Dialog.toast(response.message, {"intent":"warn"});
                    }
                },null,null,false);
                var content = template("addFormTpl", {data: editInfo});
                console.log(content)
                app.addDrawer.renderOption({title: "修改", content: content});
                app.addDrawer.open();
                var equipments = [];
                global.get("/admin/equipment/listAll?projectId="+projectId,function (res) {
                    if (res.success) {
                        res.data.equipments.forEach(item=>{
                            var m = {};
                            m.id = item.id;
                            m.text = item.name;
                            if(editInfo.equipmentId==item.id){
                                m.selected=true;
                            }
                            equipments.push(m);
                        });
                    } 
                },null,null,false);
                $("#equipmentId").select2({
                    data:equipments,
                    minimumResultsForSearch: -1
                });
            });
            // 单个删除
            $(document).on('click', ".del-single", function () {
                var equipmentMaintainId = $(this).attr("data-id");
                Dialog.open({
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确定删除该信息吗？</span>",
                    width: 320,
                    height: 'auto',
                    modal: true,
                    content: '<div class="padding-left-large-5">您确定要删除吗？删除后状态不可恢复。</div>',
                    button: [
                        { id: "mybtn1", label: "确认", intent: "primary", focus: true, click: function () {
                            global.delete("/admin/equipmentMaintain/delete/"+equipmentMaintainId,response=>{
                                if(response.success){
                                    app.addDrawer.close();
                                    table21.ajax.reload(null,false);
                                }else{
                                    alert(response.message);
                                }
                            })
                         } },
                        { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                });
            });
            // 搜索筛选
            $(".aidicon-magnify").on("click", function () {
                var searchVal = $("#search_val").val();
                param.keyword = searchVal;
                table21.ajax.reload();
            });
            $("#search_val").on("keyup", function (event) {
                if (event.keyCode == "13") {
                    var searchVal = $("#search_val").val();
                    console.log(searchVal);
                    param.keyword = searchVal;
                    table21.ajax.reload();
                }
            });
            //去掉搜索框内容
            $('.searchbox .aidicon-close').on('mousedown', function () {
                $(this).siblings('input').val('');
            });
            // 点击气泡中的取消
            $(document).on("click", ".cancel", function() {
                $(this).parents(".popover").remove();
            });
            // 点击气泡中的确定
            $(document).on("click", ".delete-classify", function(e) {
                var id = $(this).data("id");
                global.delete("/admin/equipmentMaintain/param/delete/" + id,function(res){
                    if(res.success){
                        app.initClassifyTable(globalEquipmentMaintainId);
                    }else{  
                        alert(res.message);
                    }
                })
                $(this).parents(".popover").remove();
            });
            // 参数设置
            $(document).on("click", ".classify", function () {
                var equipmentMaintainId = $(this).data("id");
                globalEquipmentMaintainId = equipmentMaintainId;
                Dialog.open({
                    theme: "classifyDialog",
                    id: 'dialog-example11',
                    title: '参数设置',
                    width: 700,
                    height: 600,
                    modal: true,
                    context: self,
                    content: template("classifyTpl"),
                    onShow: function () {
                        app.initClassifyTable(globalEquipmentMaintainId);
                    },
                    onClosed: function () {
                    }
                });
            });
            $(document).on('click','.classify-edit',function(e){
                var name =$(this).attr("data-name");
                var value =$(this).attr("data-value");
                var sort =$(this).attr("data-sort");
                var id = $(this).attr("data-id");
                $("#name").val(name)
                $("#value").val(value)
                $("#sort").val(sort)
                $("#id").val(id)
            })
            $(document).on('click','#addClassify',function(e){
                $("#name").val(null)
                $("#value").val(null)
                $("#sort").val(null)
            })
            $(document).on('click',".saveOrUpdateClassName",function(e){
                if (!$("#paramForm").valid()) {
                    return false;
                }
                var data = {};
                data.id=$("#id").val()
                data.name=$("#name").val()
                data.value=$("#value").val()
                data.sort=$("#sort").val()
                data.equipmentMaintainId=globalEquipmentMaintainId
                global.post("/admin/equipmentMaintain/param/saveOrUpdate",function(res){
                    if(res.success){
                        $('#editModal').modal('hide');
                        app.initClassifyTable(globalEquipmentMaintainId);
                    }else{
                        alert(res.message)
                    }
                },JSON.stringify(data));

            })
        }

    };
    return app;
});